<template>
  <div
    ref="myChartsRef"
    :style="{ height: height, width: width }"
    class="echarts"
  ></div>
</template>
<script setup>
import { nextTick } from "vue";
const emit = defineEmits(["click_Fun"]);
const { appContext } = getCurrentInstance();
const { $echarts } = appContext.config.globalProperties;

const props = defineProps({
  width: {
    default: "100%",
    type: String,
  },
  height: {
    default: "100%",
    type: String,
  },
  option: {
    type: Object,
    default: {},
  },
});

const myChartsRef = ref();
const myChart = shallowRef();
// 初始化echarts
const initChart = () => {
  // 拿到option配置项，渲染echarts
  myChart.value?.setOption(props.option);
};

// 渲染echarts
const resizeChart = () => {
  myChart.value = $echarts.getInstanceByDom(myChartsRef.value);
  if (myChart.value !== undefined) {
    myChart.value.dispose();
  }
  myChart.value = $echarts.init(myChartsRef.value, null, {
    renderer: "svg",
  });
  myChart.value.on("click", (val) => {
    emit("click_Fun", val);
  });
  if (myChart.value) {
    initChart();
  }
};
onMounted(() => {
  resizeChart();
  window.addEventListener("resize", resizeChart);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeChart);
});
watch(
  () => props.option,
  (val) => {
    //// console.log(val);
    nextTick(() => {
      if (myChart.value) {
        initChart();
      }
    });
  },
  {
    deep: true,
  }
);
</script>
<style scoped>
.echarts {
  width: 100%;
  height: 100%;
}
</style>
